package ink.yql.controller;

import ink.yql.model.User;
import ink.yql.service.UserService;
import ink.yql.util.RestObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/login/pwd/{phone}/{pwd}/{sendTime}")
    @ResponseBody
    public RestObject loginPwd(@PathVariable("phone") String phone, @PathVariable("pwd") String pwd, @PathVariable("sendTime") Long sendTime) {
        // 保护措施  以防拿到url一直请求
        if (System.currentTimeMillis() / 1000 - sendTime > 3) {
            return RestObject.builder().code("400").message("请求时间超时").build();
        }
        return userService.loginByPhoneAndPwd(phone, pwd);
    }

    @GetMapping("/login/code/{phone}/{code}/{sendTime}")
    @ResponseBody
    public RestObject loginCode(@PathVariable("phone") String phone, @PathVariable("code") String code, @PathVariable("sendTime") Long sendTime) {
        // 保护措施  以防拿到url一直请求
        if (System.currentTimeMillis() / 1000 - sendTime > 3) {
            return RestObject.builder().code("400").message("请求时间超时").build();
        }
        return userService.loginByPhoneAndCode(phone, code);
    }

    @GetMapping("/login/code/{phone}/{sendTime}")
    @ResponseBody
    public RestObject loginCode(@PathVariable("phone") String phone, @PathVariable("sendTime") Long sendTime) {
        // 保护措施  以防拿到url一直请求
        if (System.currentTimeMillis() / 1000 - sendTime > 3) {
            return RestObject.builder().code("400").message("请求时间超时").build();
        }
        return userService.loginSendCode(phone);
    }

    @GetMapping("/{id}/{sendTime}")
    @ResponseBody
    public RestObject getById(@PathVariable("id") Integer id, @PathVariable("sendTime") Long sendTime) {
        // 保护措施  以防拿到url一直请求
        if (System.currentTimeMillis() / 1000 - sendTime > 3) {
            return RestObject.builder().code("400").message("请求时间超时").build();
        }
        return userService.getById(id);
    }

    @PutMapping("/{sendTime}")
    @ResponseBody
    public RestObject updateUser(@RequestBody User user, @PathVariable("sendTime") Long sendTime) {
        // 保护措施  以防拿到url一直请求
        if (System.currentTimeMillis() / 1000 - sendTime > 3) {
            return RestObject.builder().code("400").message("请求时间超时").build();
        }
        return userService.updateById(user);
    }

    @GetMapping("/logout/{sendTime}")
    @ResponseBody
    public RestObject logout(@PathVariable("sendTime") Long sendTime) {
        // 保护措施  以防拿到url一直请求
        if (System.currentTimeMillis() / 1000 - sendTime > 3) {
            return RestObject.builder().code("400").message("请求时间超时").build();
        }
        return userService.logout();
    }
}
